import sys
import os
import asyncio
import aiomysql
import shutil

sys.path.append("/app")

from configs import config

async def rebuild_db(db_config, app_dir="/app"):
    try:
        os.remove(f"{app_dir}/pyproject.toml")
    except:
        pass
    try:
        shutil.rmtree(f"{app_dir}/migrations")
    except:
        pass
    conn = await aiomysql.connect(host=db_config['host'],
                                  user=db_config['user'],
                                  password=db_config['password'],
                                  port=int(db_config['port']))
    db = db_config["database"]
    async with conn.cursor() as cursor:
        await cursor.execute(f"DROP DATABASE IF EXISTS {db}")
        await cursor.execute(f"CREATE DATABASE {db} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
        await conn.commit()
        
    conn.close()

# 数据库配置
db_config = {
    'host': os.environ["mysql_host"],
    'port': os.environ["mysql_port"],
    'user': os.environ["mysql_user"],
    'password': os.environ["mysql_password"],
    'database': os.environ["mysql_database"]
}

if __name__ == "__main__":
    func = globals().get(sys.argv[1])
    asyncio.run(func(db_config))